package com.remoter.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.remoter.basic.configure.IConfiguration;
import com.remoter.basic.configure.support.AbstractConfiguration;
import com.remoter.basic.context.IContext;
import com.remoter.basic.util.Final;
import com.remoter.basic.util.ServiceLoader;

/**
 * @author			koko
 * @date 			2017-08-10 17:49:25
 * @description 	类功能说明
 */
public class BootStrap {
	
	private static final Logger logger = LoggerFactory.getLogger(BootStrap.class);
	private static volatile boolean running = true;
	
	public static void main(String[] args){
		initConfiguration(args);
		IConfiguration configuration = AbstractConfiguration.getConfiguration();
		
		final IContext context = ServiceLoader.getService(IContext.class,configuration.getOption(Final.O_VAL_CONTEXT));
		if(null == context){
			throw new IllegalArgumentException("context not found");
		}
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run(){
				try{
					context.close();
				}catch(Exception e){
					logger.error(e.getMessage(),e);
				}
				synchronized(BootStrap.class){
					running = false;
					BootStrap.class.notify();
				}
			}
		});
		synchronized(BootStrap.class){
			while(running){
				try{
					BootStrap.class.wait();
				}catch(Exception e){}
			}
		}
	}
	
	protected static void initConfiguration(String[] args){
		String name = Final.D_VAL_CONFIGURATION_NAME;
		String path = Final.D_VAL_CONFIGURATION_PATH;
		if(null != args){
			if(args.length == 1){
				String temp = args[0];
				if(temp.startsWith(".")){
					path = temp.substring(1);
				}else if(temp.endsWith(".")){
					name = temp.substring(0,temp.length()-1);
				}else{
					if(temp.indexOf(".")>0){
						String[] config = temp.split("\\.");
						name = config[0];
						path = config[1];
					}else{
						path = temp;
					}
				}
			}else if(args.length == 2){
				name = args[0];
				path = args[1];
			}
		}
		System.setProperty(Final.D_KEY_CONFIGURATION_NAME,name);
		System.setProperty(Final.D_KEY_CONFIGURATION_PATH,path);
		logger.info(String.format("set property %s=%s",Final.D_KEY_CONFIGURATION_NAME,name));
		logger.info(String.format("set property %s=%s",Final.D_KEY_CONFIGURATION_PATH,path));
	}
	
}